<template>
  <div class="flex autoRefresh">
    <div>是否自动刷新：</div>
    <el-switch v-model="isAction" @change="handleChangeAutoRefresh" style="margin-right: 10px;" />
    <el-input-number :disabled="isAction" v-model="time" size="small" controls-position="right" />
    <div style="margin-left: 5px;">秒后自动刷新</div>
  </div>
</template>

<script setup name="autoRefresh">
/**
 * 自动刷新组件
 * import AutoRefresh from "@/components/autoRefresh/index.vue"
 * <auto-refresh ref="autoRefreshRef" :time="8" @task="getList"/>
 * const getList = () => { autoRefreshRef.value.start() }
 */
import { defineEmits, onBeforeUnmount, defineExpose, defineProps} from 'vue'
import useInterval from '@/hooks/useInterval'
const props = defineProps(['time'])
const emit = defineEmits(["task"]);

const {
  isAction,
  time,
  stop,
  start
} = useInterval(props.time, () => {
  emit('task')
})

const handleChangeAutoRefresh = (e) => {
  return e ? start() : stop()
}

onBeforeUnmount(() => {
  stop()
})

defineExpose({
  start,
})
</script>

<style scoped>
.autoRefresh {
  display: flex;
  align-items: center;
}
</style>
